﻿import * as types from './actionTypes'


function selectData(state, currentData) {
    return { ...state, currentData }
}

function setChart(state, chartName) {
    return { ...state, chartName }
}

function modifyDataAttr(state, attrName, value) {
    var { currentData, dataset } = state;
    var newData = { ...currentData, [attrName]: value };
    var newDataset = dataset.map(d => (d === currentData ? newData : d));
    return {
        ...state,
        currentData: newData,
        dataset: newDataset
    }
}

function clickCol(state, index) {
    var { currentData } = state;
    if (currentData.currentCol === index) {
        var header = currentData.headers[index];

        // calc new order
        var { order: oldOrder } = header;
        var order = !(oldOrder === true);

        // reconstruct headers
        var headers = currentData.headers.map(h => {
            return h === header ? { ...header, order } : h;
        })
        // reconstruct rows
        var rows = currentData.rows.slice();
        rows.sort(order === true ? compareAsc : compareDesc);
        // build new dataset
        var data = { ...currentData, rows, headers };
        var dataset = state.dataset.map(d => {
            return d === currentData ? data : d
        })
        return { ...state, dataset, currentData: data }
        function compareAsc(a, b) { return a[index] - b[index] }
        function compareDesc(a, b) { return b[index] - a[index] }
    } else {
        return modifyDataAttr(state, 'currentCol', index);
    }
}

export default (state = null, action) => {
    switch (action.type) {
        case types.SELECT_DATA:
            return selectData(state, action.data);
        case types.SET_CHART:
            return setChart(state, action.chartName);
        case types.SELECT_ROW:
            return modifyDataAttr(state, 'currentRow', action.index);
        case types.CLICK_COL:
            return clickCol(state, action.index);
        default:
            return state;
    }
}